package org.jflame.auth;

import org.jflame.auth.authz.Permit;
import org.jflame.auth.authz.UrlPermit;
import org.jflame.commons.util.CollectionHelper;

import java.util.Collection;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;

public final class AuthorityUtils {

    public static boolean hasPermissionByUrl(Set<? extends UrlPermit> userFuns, String checkUrl) {
        boolean hasRight = false;
        if (CollectionHelper.isNotEmpty(userFuns)) {
            for (UrlPermit sysFun : userFuns) {
                // hasRight = isExistMatchedUrl(sysFun.getFunUrls(), checkUrl);
                if (sysFun.implies(checkUrl)) {
                    break;
                }
            }
        }
        return hasRight;
    }

    public static boolean hasStringPermission(Set<? extends UrlPermit> permits, String... permitStr) {
        boolean hasRight = false;
        if (CollectionHelper.isNotEmpty(permits)) {
            for (UrlPermit fun : permits) {
                if (ArrayUtils.contains(permitStr, fun.getName())) {
                    hasRight = true;
                    break;
                }
            }
        }
        return hasRight;
    }

    /**
     * 判断是否有权限
     * 
     * @param permits
     * @param p
     * @return
     */
    public static boolean implies(Collection<? extends Permit> permits, Permit p) {
        if (CollectionHelper.isEmpty(permits)) {
            return false;
        }
        for (Permit permit : permits) {
            if (permit.implies(p)) {
                return true;
            }
        }
        return false;
    }
}
